package com.aigou.service.impl;

import com.aigou.pojo.Goods;
import com.aigou.pojo.Order;
import com.aigou.pojo.OrderDetail;
import com.aigou.dao.OrderMapper;
import com.aigou.exception.AigouException;
import com.aigou.pojo.User;
import com.aigou.service.GoodsService;
import com.aigou.service.IOrderDetailService;
import com.aigou.service.IOrderService;
import com.aigou.service.UserService;
import com.aigou.vo.CartVo;
import com.aigou.vo.GoodsVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cw
 * @since 2024-05-08
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    UserService userService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    IOrderDetailService orderDetailService;
    @Autowired
	StringRedisTemplate redisTemplate;

    @Override
    @Transactional
    public void create(Order order) {

//        User user = userService.findOne(order.getUid());
//        order.setUname(user.getUsername());
//        Goods goods = goodsService.findOne(order.getGid());
//        order.setGname(goods.getName());
//        // TODO 价格处理
//        order.setPrice(goods.getSellPrice().intValue());
//        order.setPriceLow(goods.getLowPrice().intValue());
//        BigDecimal youhuiPrice = goods.getSellPrice().subtract(new BigDecimal(order.getPriceChengjiao()));
//        order.setPriceYouhui(youhuiPrice.intValue());
//        LocalDateTime now = LocalDateTime.now();
//        order.setCreateTime(now);
//        order.setStatus(0);
//        order.setPayStatus(0);
//        order.setIsDelete(0);
//        order.setWuliuStatus(0);
//        order.setPayTime(null);
//
//        this.save(order);

        // 修改商品数量
//        goodsService.updateNum(order.getGid(), goods.getNum() - order.getNum(), goods.getVersion());
    }

    @Transactional
	@Override
	public void create(CartVo cartVo) {
    	
    	// 重新查询数据库，计算金额和数量
        List<Integer> gids = cartVo.getGoodsList().stream().map((g) -> g.getGid()).collect(Collectors.toList());
        List<Goods> dbGoodsList = goodsService.findByIds(gids);
        for (Goods dbGoods : dbGoodsList) {
        	GoodsVo gvo = getGoodsVo(dbGoods.getId(), cartVo.getGoodsList());
        	if (dbGoods.getSellPrice().compareTo(gvo.getPrice()) != 0) {
				throw new AigouException("价格不一致");
			}
        	if (dbGoods.getNum() < gvo.getNum()) {
        		throw new AigouException("库存不足");
			}
        	
		}

		Order order = new Order();
		order.setOrderSn(cartVo.getId());
		LocalDateTime now = LocalDateTime.now();
        order.setCreateTime(now);
        order.setStatus(0);
        order.setUid(cartVo.getUid());
        order.setPayStatus(0);
        order.setIsDelete(0);
        order.setWuliuStatus(0);
        order.setPayTime(null);

        // 重新判断商品价格
        
        // 计算价格
        Optional<BigDecimal> optional = cartVo.getGoodsList().stream().map((g) -> {
			if (g.getPrice() == null) {
				g.setPrice(new BigDecimal(0));
			}
			return g.getPrice().multiply(new BigDecimal(g.getNum()));
		}).reduce((x,y) -> x.add(y));
        
        Integer cjjPrice = optional.get().multiply(new BigDecimal(100)).intValue();
        order.setPriceChengjiao(cjjPrice);
        this.save(order);
        
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (GoodsVo goods : cartVo.getGoodsList()) {
        	OrderDetail orderDetail = new OrderDetail();
        	orderDetail.setGid(goods.getGid());
        	orderDetail.setGname(goods.getGname());
        	orderDetail.setNum(goods.getNum());
        	orderDetail.setOid(order.getId());
        	
        	orderDetail.setPrice(goods.getPrice().intValue());
        	Integer goodsCjj = goods.getPrice().multiply(new BigDecimal(goods.getNum())).multiply(new BigDecimal(100)).intValue();
        	orderDetail.setPriceChengjiao(goodsCjj);
        	
        	orderDetail.setCreateTime(now);
            orderDetail.setStatus(0);
            orderDetail.setUid(cartVo.getUid());
            orderDetail.setPayStatus(0);
            orderDetail.setIsDelete(0);
            orderDetail.setWuliuStatus(0);
            orderDetail.setPayTime(null);
            orderDetailList.add(orderDetail);
		}
        // 批量创建明细
        orderDetailService.saveBatch(orderDetailList);
        
        // 修改商品数量
        for (Goods dbGoods : dbGoodsList) {
        	GoodsVo gvo = getGoodsVo(dbGoods.getId(), cartVo.getGoodsList());
        	goodsService.updateNum(dbGoods.getId(), dbGoods.getNum() - gvo.getNum(), dbGoods.getVersion());
        }
        
        // 清空购物车
        redisTemplate.delete(String.valueOf(cartVo.getUid()));
        
	}
	
	private GoodsVo getGoodsVo(Integer gid, List<GoodsVo> goodsVoList) {
		for (GoodsVo g : goodsVoList) {
			if (g.getGid().equals(gid)) {
				return g;
			}
		}
		return null;
	}
}
